#!/bin/zsh
videoSearch=$(yad --entry --text "Type your search:" --width=400 --height=100 2>/dev/null)
videoReturn=$(yad --entry --text "Return [1-20 (only numbers)] videos  : " --width=400 --height=100 2>/dev/null)
wget "https://www.youtube.com/results?search_query=$videoSearch" --quiet --output-document /tmp/ytmpvSearch 
sed -i 's/\,/\n/g;s/\"//g;s/http/\nhttp/g' /tmp/ytmpvSearch 
grep -E '^title:|.jpg|.webp' /tmp/ytmpvSearch > /tmp/ytmpvSearch2
grep -Ev 'searchRefinementCardRend|yoodle_webp_base_url' /tmp/ytmpvSearch2 > /tmp/ytmpvSearch 
while read line; do
    [[ $line =~ '^title:' ]] && 
        { 
            titles+=("$(grep -Ev 'YouTube TV|YouTube Music|Escola de Criadores de Conteúdo|YouTube Kids|YouTube para Artistas' <<< $(sed 's/.*[tT]ext\://g;s/\]$//g;s/\}$//g' <<< $line))")
            flag="true"
            continue 
        }
    [[ $line =~ '^https:' && ${flag:=true} == "true" ]] && 
        { 
            idsTrash+=("${${line//https:\/\/i.ytimg.com\/vi\//}//\/*/}")
        }
done < /tmp/ytmpvSearch
ids=(${(u)idsTrash})
[[ -d /tmp/ytmpv  ]] && cd /tmp/ytmpv || { mkdir /tmp/ytmpv ; cd /tmp/ytmpv }
for ((control=1; control<=$videoReturn; control++))
{
    if wget --quiet "https://i.ytimg.com/vi/${ids[$control]}/maxresdefault.jpg" --output-document=thumb$control.jpg; then
        convert thumb$control.jpg -resize 200x300 thumb$control.jpg
    elif wget --quiet "https://i.ytimg.com/vi/${ids[$control]}/hqdefault.jpg" --output-document=thumb$control.jpg; then
        convert thumb$control.jpg -resize 200x300 thumb$control.jpg
    elif wget --quiet "https://i.ytimg.com/vi_webp/${ids[$control]}/maxresdefault.webp" --output-document=thumb$control.webp; then
        convert thumb$control.webp thumb$control.jpg
        convert thumb$control.jpg -resize 200x300 thumb$control.jpg
    else
        print "não foi possível obter a thumb ${ids[$control]} control $control"
        continue
    fi
} |xargs
while true; do
    base="$(yad --grid-lines=vert --wrap-cols=2 --no-headers --width 1000 --height 800 \
    --list --column="thumbnail:IMG" --column="title:TXT" --column="id:TXT" <<< \
    $(for (( i=1 ; i<=$videoReturn ; i++  )); do; print -f '%b\n%s\n%s\n' "/tmp/ytmpv/thumb${i}.jpg" "$titles[$i]" "$ids[$i]"; done))"
    [[ $? == (1|252) ]] && break || mp "https://youtube.com/watch?v=${${(s:|:)base}[2]}"
done

rm thumb*.*
